package com.libraries.image.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;

import com.libraries.base.BaseActivity;
import com.libraries.helper.FileHelper;
import com.libraries.helper.Logger;
import com.libraries.image.adapter.ImageSelectAdapter;
import com.libraries.view.TitleBarView;
import com.libraries.view.toast.Toaster;
import com.example.libraries.R;

public class ImageSelectActivity extends BaseActivity implements OnClickListener {
	private ImageSelectAdapter imagerAdapter;
	private ArrayList<String> lImages;
	private boolean isMulti;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_list);
		initImageData();
		createTitleBar();
		initImageView();
	}
	
	private void initImageData(){
		lImages=new ArrayList<String>();
		FileHelper.loadLocalImages(this,refreshHandler);
		isMulti=getIntent().getBooleanExtra("isMulti", false);
		Logger.log(this, "initImageData", isMulti,lImages.size());
	}
	
	private void createTitleBar(){
		TitleBarView titleBarView = TitleBarView.getInstance();
		titleBarView.createTitle(this,R.string.gallery_name , 0);
		titleBarView.createLeftButton(R.string.do_cancel, null,0).setOnClickListener(this);
		titleBarView.createRightButton(R.string.do_okay, null, 0).setOnClickListener(this);
	}
	
	private void initImageView(){
		GridView gv_images = (GridView) findViewById(R.id.gv_images);
        imagerAdapter = new ImageSelectAdapter(this, lImages);
		gv_images.setAdapter(imagerAdapter);
	}
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_top_left) {
			setResult(FileHelper.DO_CANCEL_RESULT);
			this.finish();
		} else if (id == R.id.btn_top_right) {
			ArrayList<String> lSelected = imagerAdapter.getSelectedItems();
			if (lSelected.size()==0) {
				Toaster.show(this,R.string.please_selected_one);
				return;
			}
			if (!isMulti) {
				if (lSelected.size()>1) {
					Toaster.show(this,R.string.only_selected_one);
					return;
				}
			}
			else{
				if (lSelected.size()>5) {
					Toaster.show(this,R.string.only_selected_five);
					return;
				}
			}
			Intent intent = new Intent();
			intent.putStringArrayListExtra("result", lSelected);
			setResult(RESULT_OK, intent);
			this.finish();
		} else {
			setResult(RESULT_CANCELED);
			this.finish();
		}
	}
	
	private Handler refreshHandler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Logger.log(this, "handleMessage",imagerAdapter, lImages.size());
			lImages=(ArrayList<String>) msg.obj;
			if (imagerAdapter != null) {
				imagerAdapter.notifyDataSetChanged(lImages);
			}
		}
	};
}
